<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Register extends CI_Controller {

	public function __construct(){
    	parent::__construct();
		if(!isset($_SESSION)): session_start(); endif;
		$this->load->model('users_model');
		$this->load->helper('product_helper');
		$this->load->library('paypal_lib');
    }

	public function index($type=''){
		if(!in_array($type,array('free','vip','reseller'))){
			$data['title']= "Select your account";
			$data['main_content'] = 'signup_select_view';
			return $this->load->view('common/temp', $data);
		}
		$action = 0;
		$post_data = array();
		$post_data = $_POST;
		$data['post_data'] = $post_data;

		$data['title']= "Sign Up My Life My Eulogy";
		$data['main_content'] = 'register_view';
		$data['type'] = $type;
		// Get default MLME product details
		if($type=='vip'){
			$this->db->where('type','default');
			$this->db->where('enable',1);
			$product = $this->db->get('mlme_products')->result();
			$data['product_details'] = $product[0];
		}
		if($type=='reseller'){
			$this->db->where('type','package');
			$this->db->where('enable',1);
			$data['product_detailsA'] = $this->db->get('mlme_products')->result();
		}
		$action = $this->input->post('action');//register submit
		if($action == 1){
			return $this->save();
		}
		$this->load->view('common/temp', $data);
	}

	// Save the user data
	function save(){
		$usertype = strtolower($this->input->post('type'));
		$save = $this->users_model->create_users();
		$data = null;
		$email = $this->input->post('reg-email');
		$data['user_email'] = !empty($email) ? $email : $_SESSION['email'];
		if($save['insert']){
			switch($usertype){
				default:
				case 'free':
					$this->_free($save,$data);
					break;
				case 'reseller':
				case 'vip':
					$this->_vip($save,$usertype,$data);
					break;

			}//endswitch
		} else {
			$this->message->set('error', 'Failed to save registration. Please contact administrator.');
		}
		$data['usertype'] = $usertype;
		$data['title']= "Pay with Paypal";
		$data['main_content'] = 'register_step2_view';
		$data['user_email'] = $this->input->post('reg-email');
		$this->load->view('common/temp', $data);
	}

	//register save free
	function _free($save,&$data){
		$send_to = $this->input->post('reg-email');
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$headers .= "From: My Life My Eulogy <lalene@advanzweb.com> \r\n";
		$subject = "My Life My Eulogy - Verify Account";
		$body  = 'Your registration on mylifemyeulogy.com is almost complete.  <br/> Please click the link below to verify your account.  <br/>If the link is not clickable, please copy and paste in to the URL bar of your browser.  <br/>Thank you.<br/>';
		$url = base_url()."register/verify_account/".$save['userid'];
		$body .= "<a href=".$url.">$url</a>";
		if(mail($send_to, $subject, $body,$headers)){
			$this->message->set('success', 'Your registration is almost done, check your email to verify your account. Make sure to check your Spam folder just in case our verification email was filtered as Spam.');
		} else {
			$this->message->set('error', 'Error sending email.');
		}
		return true;
	}

	//register vip save
	function _vip($save,$usertype,&$data){

		//get total from selected products
		//in this case only one product later we will have array and total of it
		$price = Product_helper::get($this->input->post('prodid'), 'price');
		$price = $price->price;
		$order_total = $price;

		//if user has entered package code
		if( strlen($package_code = $this->input->post('package_code')) ){
			//we need to verify if package code is valid, if valid, we will make the amount 0 else amount is the vip price.
			$code = $this->getCodeDetails($package_code);
			if($code['is_valid']){
				$order_total = 0;
				//insert reseller_user table
				$resell_data['userproductid'] = $code['userproductid'];
				$resell_data['customerid'] = $save['real_userid'];
				$this->db->insert('mlme_usersproduct_customers', $resell_data);
			}
		}
		$data['order_total'] = $order_total;
		//save order or transaction details if total amount > 0 and then proceed to paypal checkout
		if($order_total > 0){
			$transacData = array();
			$transacData['userid'] = $save['real_userid'];
			$transacData['productid'] = $this->input->post('prodid');
			$pcode = $this->input->post('package_code');
			$transacData['package_code_entered'] =  !empty($pcode) ? $pcode : '';

			$stamp = strtotime("now");
			$ip = Product_helper::getIP();
			$ordernum = 'T'.($stamp-@$ip);
			$ordernum = str_replace(".", "", $ordernum);
			$transacData['order_number'] = $ordernum;

			$product_name = Product_helper::get($this->input->post('prodid'), 'name');
			$transacData['order_total'] = $order_total;
			$transacData['order_currency'] = $this->config->item('currency');
			$transacData['order_status'] = 'pending'; //not payed, by default
			$transacData['date_created'] = date('y-m-d h:m:s');
			$transacData['date_modified'] = date('y-m-d h:m:s');
			$transacData['modifiedby'] = $save['real_userid'];;
			$transacData['ip_address'] = $ip;
			$transacData['productid'] = $this->input->post('prodid');	//for now only one
			$transacData['qty'] = 1;  //for now only one
			$transacData['item_price'] = $price;  //for now same
			$transacData['order_type'] = $usertype;

			//Save transaction
			$this->db->insert('mlme_orders', $transacData);
			//proceed to checkout
			//to be sent to paypal post
			$custom = null;
			$custom->userid = $transacData['userid'];
			$email = $this->input->post('reg-email');
			$custom->user_email = !empty($email) ? $email : $_SESSION['email'];
			$custom->orderid = $this->db->insert_id();
			$custom->usertype = $usertype;
			$custom->productid = $transacData['productid'];
			$qty = Product_helper::get($this->input->post('prodid'), 'quantity');
			$custom->accounts_qty = $qty->quantity;
			$custom = json_encode($custom);

			$this->setPaypalForm($product_name->name,$transacData['productid'],$transacData['item_price'], $custom);
			$data['paypal_form'] = $this->paypal_lib->paypal_form();
			if($usertype=='vip'){
				$this->message->set('success', 'Your account has been created. Please secure your payment to be a VIP account holder and enjoy the VIP features of My Life My Eulogy Website.');
			} elseif($usertype=='reseller'){
				$this->message->set('success', 'Your account has been created. Please secure your payment to BUSINESS with us.');
			} else{
				$this->message->set('error', 'Invalid user type. Contact Administrator');
			}

		} else {
			$this->message->set('success', 'Your account has been created. Welcome and enjoy the VIP features of My Life My Eulogy Website.');
		}
		return true;
	}

	public function captcha_validate(){
	  $this->load->helper("captcha");
	  print_r(my_sessions());
	}

	function email_exist(){
		$email = $this->input->post('reg-email');
		$check = $this->users_model->check_email($email);
		echo ($check)? 'true':'false';
	}

	function verify_account($encrypted_id){
		$verify = $this->users_model->verify_account($encrypted_id);
		$con_msg = (isset($_SESSION['sess_con_msg']))? $_SESSION['sess_con_msg']:'';
		if($verify && !empty($con_msg)){
			$_SESSION['is_logged_in'] = true;
			redirect('profile');
		}else{
			redirect('login');
		}//end if
	}

	//Set paypalform fields
	function setPaypalForm($item_name='', $item_number='', $amount='', $custom=''){
		$business = 'lalene_1328513880_biz@advanzweb.com';
		//$this->paypal_lib->add_field('business', $this->config->item('merchant_paypal'));
		$this->paypal_lib->add_field('business', $business);
	    $this->paypal_lib->add_field('return', site_url('register/paypal/success'));
	    $this->paypal_lib->add_field('cancel_return', site_url('register/paypal/cancel'));
	    $this->paypal_lib->add_field('notify_url', site_url('register/paypal/ipn')); // <-- IPN url

	    $this->paypal_lib->add_field('custom', $custom); // <-- Verify return
	    $this->paypal_lib->add_field('item_name', $item_name);
	   // $this->paypal_lib->add_field('item_number', $item_number);
	    $this->paypal_lib->add_field('amount', $amount);

		$this->paypal_lib->image('reg-paypal-btn.png');

		// otherwise, don't write anything or (if you want to
		// change the default button text), write this:
		// $this->paypal_lib->button('Click to Pay!');
		return true;
	}

	/**
	 * Paypal method used to call this function when calling paypal methods
	 */
	 function paypal($task){
	 	switch($task){
	 		case 'success':
	 			$this->_success();
	 			break;
	 		case 'cancel':
	 			$this->_cancel();
	 			break;
	 		case 'ipn':
	 			$this->_ipn();
	 			break;

	 	}
	 }

	function _cancel(){
		redirect(base_url());
	}

	function _success(){
		// This is where you would probably want to thank the user for their order
		// or what have you.  The order information at this point is in POST
		// variables.  However, you don't want to "process" the order until you
		// get validation from the IPN.  That's where you would have the code to
		// email an admin, update the database with payment status, activate a
		// membership, etc.

		// You could also simply re-direct them to another page, or your own
		// order status page which presents the user with the status of their
		// order based on a database (which can be modified with the IPN code
		// below).

		$pp_info = $this->input->post();
		if(empty($pp_info)){
			$pp_info = $_POST;
		}
//		print_r($pp_info);
		if(empty($pp_info)){
			redirect(base_url());
		}
		$custom = json_decode($pp_info['custom']);
		$userid = $custom->userid;

		//check if this user is already active
		$this->db->select('email');
		$this->db->where('userid', $userid);
		$this->db->where('status', 1);
		$result = $this->db->get('mlme_users')->result();
		if(!empty($result[0]->email)){
			//enable session, ready for logging in
			$_SESSION['is_logged_in'] = TRUE;
			$_SESSION['email'] = $custom->user_email;
			redirect(base_url().'profile');
		} else {
			redirect(base_url());
		}
	}

	 function _ipn(){
		// Payment has been received and IPN is verified.  This is where you
		// update your database to activate or process the order, or setup
		// the database with the user's order details, email an administrator,
		// etc. You can access a slew of information via the ipn_data() array.

		// Check the paypal documentation for specifics on what information
		// is available in the IPN POST variables.  Basically, all the POST vars
		// which paypal sends, which we send back for validation, are now stored
		// in the ipn_data() array.

		// For this example, we'll just email ourselves ALL the data.

		if ($this->paypal_lib->validate_ipn()){
			$pp_info = $this->paypal_lib->ipn_data;
			$custom = json_decode($pp_info['custom']);

			//update membership status
			$userid = $custom->userid;
			$postData = array();
			//if payment = completed, activate status else deactivate
			if(strtolower($pp_info['payment_status']) == 'completed'){
				$postData['status'] = 1;
			} else {
				$postData['status'] = 0;
			}
			if($custom->usertype == 'free') //upgrade to vip
				$postData['type'] = 'vip';
			$this->db->where('userid', $userid);
			$this->db->update('mlme_users',$postData );
			$postData = array();
			$postData['order_status'] = strtolower($pp_info['payment_status']);
			$this->db->where('orderid', $custom->orderid);
			$this->db->update('mlme_orders',$postData );

			//perhaps email an admin that new user has paid, or sign up
			$adminEmail = 'noel@advanzweb.com';
			$is_notified = $this->_sendMail($custom->user_email);//user
			$this->_sendMail($adminEmail,1);//admin

			//populate usersproduct table if reseller
			if($custom->usertype == 'reseller'){
				$postData = array();
				$postData['userid'] = $userid;
				$postData['productid'] = $custom->productid;
				$postData['accounts_qty'] = $custom->accounts_qty;
				$postData['status'] = 1;
				$this->db->insert('mlme_usersproduct',$postData );
				$upid = $this->db->insert_id();
				//insert code
				$postData = array();
				$postData['code'] = $this->generatePackCode($upid);
				$this->db->where('userproductid',$upid );
				$this->db->update('mlme_usersproduct',$postData );
			}

			//insert table order_history
			$postData = array();
			$postData['orderid'] = @$custom->orderid;
			$postData['status'] = strtolower($pp_info['payment_status']);
			$postData['date_added'] = @$pp_info['payment_date'];
			$postData['customer_modified'] = $is_notified;
			$postData['comments'] = @$pp_info['memo'];
			$this->db->insert('mlme_order_history',$postData );
		}
		return true;
	}

	//check if package code is valid
	//return json
	function packagecode_valid(){
		$package_code = $this->input->post('package_code');
		$qstr = "SELECT a.userproductid, a.accounts_qty, b.firstname as owner_fname, b.lastname as owner_lname" .
				" FROM mlme_usersproduct a, mlme_users b" .
				" WHERE a.code = '$package_code' AND a.status = 1 AND a.userid = b.userid " .
				" LIMIT 1";
	 	$result = $this->db->query($qstr);
		$owner_name = '';
		$is_valid = false;
		if($result->num_rows > 0){
			$code_detail = $result->result();
			if( $code_detail[0]->accounts_qty - $this->countRegistered($code_detail[0]->userproductid) > 0 ){
				$is_valid = true;
				$owner_name = $code_detail[0]->owner_fname.' '.$code_detail[0]->owner_lname;
			}
		}
		echo json_encode( array('is_valid'=>$is_valid, 'owner'=>$owner_name) );
		exit;
	}

	//check if package code is valid
	//return array
	function getCodeDetails($package_code){
		$this->db->select('accounts_qty');
		$this->db->select('userproductid');
		$this->db->select('userid');
		//if code exists
		$this->db->where('code',$package_code);
		//if pubished
		$this->db->where('status',1);
		//if ramaining qty > 0
		$this->db->limit(1);
		$result = $this->db->get('mlme_usersproduct');
		$is_valid = false;
		if($result->num_rows > 0){
			$code = $result->result();
			//if remaining acnt > 0, invalid
			if( $code[0]->accounts_qty - $this->countRegistered($code[0]->userproductid) > 0 ){
				$is_valid = true;
			}
		}
		$userproductid = isset($code[0]->userproductid) ? $code[0]->userproductid : '';
		$resellerid = isset($code[0]->userid) ? $code[0]->userid : '';
		$remaining = isset($code[0]->remaining_qty) ? $code[0]->remaining_qty : '';
		return array('is_valid'=>$is_valid,'userproductid'=>$userproductid,'resellerid'=>$resellerid,'remaining'=>$remaining);
	}

	//count how many accounts registered in this userproductid of the reseller
	function countRegistered($id){
		if(empty($id)) return 0;
		$qstr = "SELECT COUNT(a.customerid) as numRegistered FROM mlme_usersproduct_customers a" .
				" WHERE a.userproductid=$id " ;
	 	$qry = $this->db->query($qstr);
	 	$result = $qry->result();
	 	return $result[0]->numRegistered;
	}

	function _sendMail($send_to,$isAdmin=false){


		//		$to    = 'lalene@advanzweb.com';    //  your email
//
//		if ($this->paypal_lib->validate_ipn())
//		{
//			$body  = 'An instant payment notification was successfully received from ';
//			$body .= $this->paypal_lib->ipn_data['payer_email'] . ' on '.date('m/d/Y') . ' at ' . date('g:i A') . "\n\n";
//			$body .= " Details:\n";
//
//			foreach ($this->paypal_lib->ipn_data as $key=>$value)
//				$body .= "\n$key: $value";
//
//			// load email lib and email results
//			$this->load->library('email');
//			$this->email->to($to);
//			$this->email->from($this->paypal_lib->ipn_data['payer_email'], $this->paypal_lib->ipn_data['payer_name']);
//			$this->email->subject('CI paypal_lib IPN (Received Payment)');
//			$this->email->message($body);
//			$this->email->send();
//		}



		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
		$headers .= "From: My Life My Eulogy\r\n";
		$body='';
		if($isAdmin){
			$subject  = "New User have registered and successfully paid";
			$body.='Hi,</b>,';
			$body.="<br/><br/>New user have successfully registered and paid. Below are the details:";
			foreach ($this->paypal_lib->ipn_data as $key=>$value){
				$body .= "\n$key: $value";
			}
		}else{
			$this->load->model('lib_model');
			$userInfo = $this->lib_model->get('mlme_users','firstname,lastname','email',$send_to);
			$userName = $userInfo[0]->firstname.' '.$userInfo[0]->lastname;
			$subject  = "You have successfully registered and paid";
			$link = '<a href='.base_url().'>click here</a>';
			$body.='Hi <b>'.ucfirst($userName).'</b>,';
			$body.='<br/><br/>You have successfully registered and paid';
			$body.='<br>'.$link.' to login';
		}
		return mail($send_to, $subject, $body,$headers);
	}

	//upgrade to vip account
	function upgrade(){
		$this->db->where('type','default');
		$this->db->where('enable',1);
		$product = $this->db->get('mlme_products')->result();
		$data['product_details'] = $product[0];
		$param = null;
		$data['real_userid'] = Myuser_helper::get_userid($_SESSION['email']);
		$data['title']= "Upgrade to VIP Account";
		$this->load->view('upgrade/index',$data);
	}//end fct

	function saveUpgrade(){
		$save = null;
		$save['real_userid'] = $this->input->post('real_userid');
		$usertype = 'free';
		$data['params'] = $this->input->post();
		$return = $this->_vip($save,$usertype,$data );
		$this->load->view('upgrade/payupgrade',$data);
	}
	// upgrade to vip if code is valid
	function upgradeAcnt(){
		$postData = $this->input->post();
		$code = $this->getCodeDetails($postData['package_code']);
		//insert reseller_user table
		$resell_data['userproductid'] = $code['userproductid'];
		$resell_data['customerid'] = $this->input->post('real_userid');
		$this->db->insert('mlme_usersproduct_customers', $resell_data);
		$data = null;
		$data['type'] = 'vip';
		$this->db->where('userid', $this->input->post('real_userid'));
		$this->db->update('mlme_users',$data );
		echo true;
	}

	//Generate the reseller's code , get the hash base on the primary key value
	function generatePackCode($upid){
		return hash(crc32,hash(crc32b,$upid));
	}

}//endclass

